package com.gylang.print.richtext.component;

import lombok.Data;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

/**
 * @author gylang
 * data 2021/7/13
 */
@Data
public class BaseRichImage extends BaseRich {

	private String src;

	private String alt;

	private String href;

	private BufferedImage image;

	private boolean init;

	private boolean percent;

	@Override
	public float width() {
		if (!percent) {
			return get(WIDTH);
		}
		BufferedImage image = getImage();
		if (null == image) {
			return 0;
		}
		return image.getWidth() * getNullDefault(WIDTH, 100F) / 100;
	}

	@Override
	public float height() {
		if (!percent) {
			return get(HEIGHT);
		}
		BufferedImage image = getImage();
		if (null == image) {
			return 0;
		}
		return image.getWidth() * getNullDefault(HEIGHT, 100F) / 100;
	}

	@Override
	public boolean notFillBr() {
		return true;
	}

	public BufferedImage getImage() {

		if (null == image && !init) {
			try {
				init = true;
				image = ImageIO.read(new URL(src));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return image;
	}
}
